#!/usr/bin/env python3
"""
CSV工具模块 - 解决中文编码问题，确保Excel能正确显示
"""

import csv
import pandas as pd
from typing import List, Dict, Any, Optional
from pathlib import Path

def write_csv_excel_friendly(file_path: str, data: List[List[Any]], headers: Optional[List[str]] = None):
    """
    写入Excel友好的CSV文件（UTF-8 BOM编码）
    
    参数:
        file_path: 输出文件路径
        data: 数据行列表
        headers: 表头列表（可选）
    """
    with open(file_path, 'w', newline='', encoding='utf-8-sig') as f:
        writer = csv.writer(f)
        
        # 写入表头
        if headers:
            writer.writerow(headers)
        
        # 写入数据
        for row in data:
            writer.writerow(row)
    
    print(f"📄 Excel友好的CSV文件已保存: {file_path}")

def append_csv_excel_friendly(file_path: str, data: List[List[Any]]):
    """
    追加数据到Excel友好的CSV文件
    
    参数:
        file_path: 文件路径
        data: 要追加的数据行列表
    """
    # 追加模式使用utf-8（文件创建时已经有BOM头）
    with open(file_path, 'a', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        for row in data:
            writer.writerow(row)

def read_csv_with_encoding_detection(file_path: str) -> pd.DataFrame:
    """
    智能读取CSV文件，自动检测编码
    
    参数:
        file_path: CSV文件路径
        
    返回:
        pandas DataFrame
    """
    encodings = ['utf-8-sig', 'utf-8', 'gbk', 'gb2312', 'cp936']
    
    for encoding in encodings:
        try:
            df = pd.read_csv(file_path, encoding=encoding)
            print(f"✅ 使用编码 {encoding} 成功读取文件: {file_path}")
            return df
        except (UnicodeDecodeError, UnicodeError):
            continue
    
    # 如果所有编码都失败，使用错误处理
    try:
        df = pd.read_csv(file_path, encoding='utf-8', errors='replace')
        print(f"⚠️ 使用UTF-8 + 错误替换模式读取文件: {file_path}")
        return df
    except Exception as e:
        raise Exception(f"无法读取CSV文件 {file_path}: {str(e)}")

def convert_csv_encoding_for_excel(input_file: str, output_file: Optional[str] = None):
    """
    转换CSV文件编码为Excel友好格式
    
    参数:
        input_file: 输入CSV文件路径
        output_file: 输出CSV文件路径（可选，默认覆盖原文件）
    """
    if output_file is None:
        output_file = input_file
    
    # 读取原文件
    df = read_csv_with_encoding_detection(input_file)
    
    # 保存为Excel友好格式
    df.to_csv(output_file, index=False, encoding='utf-8-sig')
    
    print(f"🔄 CSV编码转换完成: {input_file} -> {output_file}")

def create_excel_friendly_csv_writer(file_path: str, headers: List[str]):
    """
    创建Excel友好的CSV写入器上下文管理器
    
    参数:
        file_path: 文件路径
        headers: 表头列表
        
    返回:
        上下文管理器
    """
    class ExcelFriendlyCSVWriter:
        def __init__(self, file_path: str, headers: List[str]):
            self.file_path = file_path
            self.headers = headers
            self.file = None
            self.writer = None
        
        def __enter__(self):
            self.file = open(self.file_path, 'w', newline='', encoding='utf-8-sig')
            self.writer = csv.writer(self.file)
            self.writer.writerow(self.headers)
            return self.writer
        
        def __exit__(self, exc_type, exc_val, exc_tb):
            if self.file:
                self.file.close()
    
    return ExcelFriendlyCSVWriter(file_path, headers)

# 示例使用方法
if __name__ == "__main__":
    # 示例1: 创建Excel友好的CSV文件
    sample_data = [
        ["问题1", "知识块1", 0.8, "相关性高"],
        ["问题1", "知识块2", 0.6, "部分相关"],
        ["问题2", "知识块3", 0.9, "高度相关"]
    ]
    
    headers = ["问题", "知识块", "评分", "理由"]
    write_csv_excel_friendly("test_excel_friendly.csv", sample_data, headers)
    
    # 示例2: 使用上下文管理器
    with create_excel_friendly_csv_writer("test_context.csv", headers) as writer:
        for row in sample_data:
            writer.writerow(row)
    
    # 示例3: 转换现有文件
    # convert_csv_encoding_for_excel("input.csv", "output_excel_friendly.csv")
    
    print("CSV工具测试完成！") 